<template>
  <el-table :data="bannerList" style="width: 100%">
    <el-table-column fixed prop="bannerid" label="轮播图编号" width="180" />
    <el-table-column label="图片" width="130">
      <template #default="scope">
        <img class="img" :src="scope.row.img" />
      </template>
    </el-table-column>
    <el-table-column prop="alt" label="图片提示" width="150" />
    <el-table-column prop="link" label="图片链接" width="300" />
    <el-table-column label="是否启用" v-if="crud.charAt(2) === '1'"
      ><template #default="scope">
        <el-switch
          v-model="scope.row.flag"
          @change="(val:any) => updateBannerFlag(scope.row.bannerid, val)"
        /> </template
    ></el-table-column>
    <el-table-column label="操作" v-if="crud.charAt(3) === '1'">
      <template #default="scope">
        <el-popconfirm
          title="亲，您真的要删除吗?"
          @confirm="deleteBannner(scope.row.bannerid)"
        >
          <template #reference>
            <el-button class="del">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang='ts'>
import { reactive, ref } from "vue";
import service from "../../../utils/service";
import { ElMessage } from "element-plus";
import "element-plus/dist/index.css";
import { useRoute } from "vue-router";
const $route = useRoute();
const crud: string = $route.meta.crud as string;
const val = ref<any>();
console.log("$route", $route);
interface IBanner {
  link: string;
  img: string;
  alt: string;
  bannerid: string;
  flag: boolean;
}

//定义轮播图数据
let bannerList = reactive<IBanner[]>([]);
//获取轮播图数据
const getBannerList = () => {
  service({
    url: "/banner/list",
  }).then((res: any) => {
    if (res.data.code === "200") {
      bannerList.length = 0;
      bannerList.push(...res.data.data);
    }
  });
};
//更新轮播图的访问状态
const updateBannerFlag = (bannerid: string, val: any) => {
  service({
    url: "/banner/updateFlag",
    method: "post",
    data: {
      bannerid: bannerid,
      flag: val,
    },
  }).then((res) => {
    if (res.data.code === "200") {
      ElMessage({
        message: "更新成功！",
        type: "success",
      });
    }
  });
};

getBannerList();
//删除
const deleteBannner = (bannerid: string) => {
  service({
    url: "/banner/delete",
    params: {
      bannerid,
    },
  }).then((res) => {
    if (res.data.code === "200") {
      ElMessage({
        message: "删除成功！",
        type: "success",
      });
      getBannerList();
    }
  });
};
</script>

<style scoped>
.img {
  width: 100%;
}
.del {
  background-color: rgb(238, 93, 93);
  color: white;
  border-radius: 10px;
}
</style>